<?php

namespace app\api\model;

use think\Model;

/**
 * 文件夹模型
 */
class Folder extends Model
{
    protected $name = 'api_folders';
    
    // 设置字段信息
    protected $schema = [
        'id'          => 'int',
        'room_id'     => 'int',
        'parent_id'   => 'int',
        'name'        => 'string',
        'path'        => 'string',
        'level'       => 'int',
        'sort_order'  => 'int',
        'audio_count' => 'int',
        'create_time' => 'bigint',
        'update_time' => 'bigint',
    ];

    // 自动时间戳（毫秒）
    protected $autoWriteTimestamp = false;

    /**
     * 获取子文件夹
     */
    public function children()
    {
        return $this->hasMany(Folder::class, 'parent_id', 'id');
    }

    /**
     * 获取父文件夹
     */
    public function parent()
    {
        return $this->belongsTo(Folder::class, 'parent_id', 'id');
    }

    /**
     * 获取文件夹下的音频文件
     */
    public function audios()
    {
        return $this->hasMany(Audio::class, 'folder_id', 'id');
    }

    /**
     * 获取指定房间的根目录文件夹
     */
    public static function getRootFolders($roomId)
    {
        return self::where('room_id', $roomId)
            ->whereNull('parent_id')
            ->order('sort_order', 'asc')
            ->select();
    }

    /**
     * 获取指定文件夹的子文件夹
     */
    public static function getChildFolders($roomId, $parentId = null)
    {
        $query = self::where('room_id', $roomId);
        
        if ($parentId === null) {
            $query->whereNull('parent_id');
        } else {
            $query->where('parent_id', $parentId);
        }
        
        return $query->order('sort_order', 'asc')->select();
    }

    /**
     * 更新音频数量统计
     */
    public function updateAudioCount()
    {
        $count = Audio::where('folder_id', $this->id)
            ->where('status', Audio::STATUS_NORMAL)
            ->count();
            
        $this->save([
            'audio_count' => $count,
            'update_time' => time() * 1000
        ]);
        
        return $count;
    }

    /**
     * 构建完整路径
     */
    public static function buildPath($parentPath, $name)
    {
        return $parentPath ? $parentPath . '/' . $name : $name;
    }

    /**
     * 获取面包屑导航
     */
    public function getBreadcrumbs()
    {
        $breadcrumbs = [];
        $current = $this;
        
        while ($current) {
            array_unshift($breadcrumbs, [
                'id' => $current->id,
                'name' => $current->name,
                'path' => $current->path
            ]);
            $current = $current->parent;
        }
        
        return $breadcrumbs;
    }
}
